import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

public class Communication extends Thread {
	
	private String host;
	private int port;
	private Queue<Message> qe;
	
	public Communication(String host, int port){
		this.host = host;
		this.port = port;
		this.qe = new LinkedList<Message>();
	}
	
	public void run(){
		ServerSocket socket = null;
		try {
			socket = new ServerSocket (port);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//System.out.println ("~~ Actor listening on " + port) ;
		java.net.Socket soc = null;
		InputStream flux = null;
		Message msg;
		while (true){ 
			try {
				soc = socket.accept();
				flux = soc.getInputStream ();
				ObjectInputStream ois = new ObjectInputStream(flux);
				msg = (Message)ois.readObject();
				qe.add(msg);
				System.out.println("Message added to queue! ("+qe.size()+")") ;
			} 
			catch (IOException e) {	e.printStackTrace(); } 
			catch (ClassNotFoundException e) { e.printStackTrace();	}
		}
	}
	
	public void deploy(){
		start();
	}
	
	public Message checkMsg(){
		Message msg = null;
		 try{
			msg = qe.remove();
		 }
		 catch(NoSuchElementException e){
			//System.out.println("Liste vide (" +  e.getMessage() + ")"); 
		 }
		 return msg;
	}

		
}
	
